package com.smilive.start.netty.jdk;

import com.smilive.start.netty.utils.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @program: netty_start
 * @Date: 2021-12-30 16:57
 * @Author: smilive
 * @Description:ByteBuffer 与字符串的相互转换
 */
@Slf4j
public class ByteBufferString {

    public static void main(String[] args) {

        //String ->ByteBuffer
        //方法1
        ByteBuffer buffer1 = ByteBuffer.allocate(10);
        buffer1.put("smilive1".getBytes());

        //切换到读模式
        buffer1.flip();
        ByteBufferUtil.debugAll(buffer1);

        //方法2: 此时获得的ByteBuffer为读模式，无需通过flip切换模式
        ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("smilive2");
        ByteBufferUtil.debugAll(buffer2);

        //方法3:此时获得的ByteBuffer为读模式，无需通过flip切换模式
        ByteBuffer buffer3 = ByteBuffer.wrap("smilive3".getBytes());
        ByteBufferUtil.debugAll(buffer3);


        //ByteBuffer -> String
        System.out.println(StandardCharsets.UTF_8.decode(buffer1).toString());
        System.out.println(StandardCharsets.UTF_8.decode(buffer2).toString());
        System.out.println(StandardCharsets.UTF_8.decode(buffer3).toString());
    }
}
